<?php
/**
 * CK 快速开发框架
 * User: Clake
 * Date: 15/6/7
 * Time: 04:03
 */

namespace CK\Util;

/**
 * Class Arr
 * 数据操作类
 * @package CK\Util
 */
class Arr {
    //默认的路径分割符
    public static $_del = '.';

    /**
     * 得到一个数组值
     *
     *
     * @param      $array
     * @param      $path   'foo.bar.xxx'
     * @param null $del
     *
     * @return null
     */
    public static function get($array,$path,$del=null) {
        if (is_array($path)) {
            $keys = $path;
        } else {
            if (array_key_exists($path, $array)) {
                return $array[$path];
            }
            if ($del === null) {
                $del = self::$_del;
            }
            $keys = explode($del, $path);
        }

        do {
            $key = array_shift($keys);
            if (isset($array[$key])) {
                if (is_array($array[$key]) && count($keys) > 0) {
                    return self::get($array[$key],$keys,$del);
                } else {
                    return $array[$key];
                }
            } else {
                break;
            }
        } while($keys);

        return null;
    }

    /**
     * 设置数组值
     *
     * @param      $array
     * @param      $path    'foo.bar.xxx'
     * @param      $value
     * @param null $del
     */
    public static function set(& $array,$path,$value,$del=null) {
        if (is_array($path)) {
            $keys = $path;
        } else {
            if ($del === null) {
                $del = self::$_del;
            }
            $keys = explode($del, $path);
        }

        $key = array_shift($keys);
        if (ctype_digit($key)) {
            $key = intval($key);
        }

        if (count($keys) > 0) {
            $array[$key] = null;
            self::set($array[$key],$keys,$value,$del);
        } else {
            $array[$key] = $value;
        }
    }

    /**
     * 合并两个数组,递归合并项目
     * @param array $arr1
     * @param array $arr2
     *
     * @return array
     */
    public static function mrg(array $arr1,array $arr2) {
        if (is_assoc($arr2)) {
            foreach ($arr2 as $key=>$value) {
                if (isset($arr1[$key]) && is_assoc($value)) {
                    $arr1[$key] = self::mrg($arr1[$key],$value);
                } else {
                    $arr1[$key] = $value;
                }
            }
            return $arr1;
        } else {
            return array_merge($arr1,$arr2);
        }
    }
}